package Mr.Right.util.enchance;

import java.sql.Connection;
import java.sql.SQLException;

import org.apache.log4j.spi.ErrorCode;

import com.mchange.v2.c3p0.ComboPooledDataSource;

public class JDBCPoolAppender extends org.apache.log4j.jdbc.JDBCAppender {

		private ComboPooledDataSource dataSource;
		
	    public JDBCPoolAppender() {   
	        super();
	    } 
	    /**
	     * 重载JDBCAppender的getConnection()方法
	     */
	    @Override
	    protected Connection getConnection() throws SQLException {
	    	
    		if(null == connection){
	    		this.connection = dataSource.getConnection();
	    	}
	        return this.connection; 
	    }
	    
	    
//	    /**
//	     * 重载getLogStatement()方法，
//	     * 在SQL字符串最后添加用户ID等信息
//	     */
//	    @Override
//	     protected String getLogStatement(LoggingEvent event) {
//	         StringBuffer stringBuffer = new StringBuffer(); 
//	         stringBuffer.append(layout.format(event)); 
//	         
//	         if (event.getMessage() instanceof ParameterizedMessage) {
//	             
//	             //检测SQL的最后一个字符是不是逗号，如果不是，则在这里补上
//	             if(stringBuffer.charAt(stringBuffer.length()-1)!=',')
//	                 stringBuffer.append(",");
//	             
//	             Object[] params = ((ParameterizedMessage) event.getMessage()).getParameters();   
//	             for (int i = 1; i < params.length; i++) { 
//	                     stringBuffer.append(params[i]);
//	                     stringBuffer.append(",");  
//	             }   
//	             
//	             stringBuffer.deleteCharAt(stringBuffer.length()-1);
//	             stringBuffer.append(")");
//	         }   
//	        return stringBuffer.toString();
//	    }
	    
	     /**
	      * 重载JDBCAppender的方法，取消与数据库的连接
	      */
	     @Override
	     protected void closeConnection(Connection con) {
	    	 flushBuffer();

	    	    try {
	    	      if (connection != null && !connection.isClosed())
	    	          connection.close();
	    	    } catch (SQLException e) {
	    	        errorHandler.error("Error closing connection", e, ErrorCode.GENERIC_FAILURE);
	    	    }
	    	    this.closed = true;
	     }


		public ComboPooledDataSource getDataSource() {
			return dataSource;
		}
		public void setDataSource(ComboPooledDataSource dataSource) {
			this.dataSource = dataSource;
		}
	     
	}  
